package com.jhh.pay.center.actor;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.common.base.Strings;
import com.jhh.pay.center.cfg.GlobalConfigProperties;
import com.jhh.pay.center.model.Order;
import com.jhh.pay.center.model.PayChannel;
import com.jhh.pay.center.model.PayChannelCfg;
import com.jhh.pay.center.model.TradeState;
import com.jhh.pay.center.service.PayChannelCfgService;
import com.jhh.pay.center.service.cloud.message.AbstractMessage;
import com.jhh.pay.center.service.cloud.message.TradeResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Map;

/**
 * @author tangxd
 * @Description: TODO
 * @date 2017/12/13
 */
@Slf4j
public abstract class TradeActor extends BaseJhhActor {

    @Autowired
    private PayChannelCfgService cfgService;

    /**
     * 设置扩展参数
     *
     * @param message
     * @param channel
     * @param order
     */
    void setMessageExtension(AbstractMessage message, PayChannel channel, Order order) {
        if (order == null) {
            return;
        }
        if (Strings.isNullOrEmpty(order.getExtension())) {
            return;
        }
        Map<String, Object> json = JSON.parseObject(order.getExtension());
//        if (json.containsKey(channel.getKey())) {
//            if (json.get(channel.getKey()) instanceof JSONObject) {
        message.setExtension(json);
//            }
//        }
    }

    /**
     * 设置通道配置参数
     *
     * @param message
     * @param channel
     * @return
     */
    boolean setChannelCfg(AbstractMessage message, PayChannel channel) {
        PayChannelCfg cfg = cfgService.get(channel.getId(), channel.getVersion());
        if (null == cfg) {
            log.warn("支付通道" + channel.getName() + "版本" + channel.getVersion() + "没有可用配置");
            sender().tell(TradeResult.create(TradeState.ERROR, "SYS:CHN:0001", "支付通道没有可用参数"), self());
            context().stop(self());
            return false;
        }
        message.setCfg(JSON.parseObject(cfg.getCfg()));
        return true;
    }
}
